package cn.edu.zut.soft.student.service.course.impl;

import cn.edu.zut.soft.student.bean.PageBean;
import cn.edu.zut.soft.student.dao.CourseMapper;
import cn.edu.zut.soft.student.model.Course;
import cn.edu.zut.soft.student.model.CourseExample;
import cn.edu.zut.soft.student.service.course.CourseBo;
import cn.edu.zut.soft.student.service.course.vo.CourseQuery;
import cn.edu.zut.soft.student.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Author ChrisPhantom
 * @ChreatDate 2021/02/20 11:06
 */

@Service
public class CourseBoImpl implements CourseBo {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public int addCourse(Course course) {
        return courseMapper.insert(course);
    }

    @Override
    public int importCourses(MultipartFile file) throws Exception {
        List<Course> courses = ExcelUtil.getCoursesFromExcel(file.getInputStream());
        courses.forEach(course -> addCourse(course));
        return 0;
    }

    @Override
    public int deleteCourse(String courseid) {
        return courseMapper.deleteByPrimaryKey(courseid);
    }

    @Override
    public int updateCourse(Course course) {
        return courseMapper.updateByPrimaryKey(course);
    }

    @Override
    public Course queryCourseById(String courseid) {
        return courseMapper.selectByPrimaryKey(courseid);
    }

    @Override
    public PageBean<List<Course>> queryCourses(CourseQuery courseQuery) {
        CourseExample courseExample = new CourseExample();
        courseExample.setOffset(courseQuery.getOffset());
        courseExample.setLimit(courseQuery.getLimit());
        CourseExample.Criteria criteria = courseExample.createCriteria();
        if (courseQuery.getCoursetype() != null && courseQuery.getCoursetype() != "") {
            criteria.andCoursetypeEqualTo(courseQuery.getCoursetype());
        }
        if (courseQuery.getCredits() != null && courseQuery.getCredits() != -1) {
            criteria.andCreditsEqualTo(courseQuery.getCredits());
        }
        if (courseQuery.getTime() != null && courseQuery.getTime() != -1) {
            criteria.andTimeEqualTo(courseQuery.getTime());
        }
        return new PageBean<>(courseMapper.selectByExample(courseExample), courseMapper.countByExample(courseExample));
    }
}
